# -*- coding: utf-8 -*-
"""
TOF测距传感器基类
提供通用的传感器接口和功能
"""
import logging
from abc import ABC, abstractmethod
from typing import Optional, Dict, Union, List

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    handlers=[logging.StreamHandler()]
)
logger = logging.getLogger("TOF_Measure")


class TOF_Measure(ABC):
    """TOF测距传感器基类，定义通用接口和功能"""
    
    def __init__(self, port: Optional[str] = None, baudrate: int = 921600):
        """
        初始化TOF传感器基类
        
        Args:
            port: 串口号（如"COM3"或"/dev/ttyUSB0"），None则自动搜索
            baudrate: 波特率
        """
        self.port = port
        self.baudrate = baudrate
        self.is_connected = False
        self.sensor_type = None
        self.available_sensors = {
            "PH2501": "PSH2501单点dToF传感器",
            "STP23L": "STP23L激光测距传感器"
        }
        
    @classmethod
    def Sensor_select(cls, sensor_type: str) -> 'TOF_Measure':
        """
        选择并创建指定类型的传感器实例
        
        Args:
            sensor_type: 传感器类型 ("PH2501" 或 "STP23L")
            
        Returns:
            对应传感器类型的实例
        """
        if sensor_type == "PH2501":
            from PH2501 import PSH2501_DToF
            return PSH2501_DToF()
        elif sensor_type == "STP23L":
            from STP23L import STP23L_RangeFinder
            return STP23L_RangeFinder()
        else:
            raise ValueError(f"不支持的传感器类型: {sensor_type}。支持的类型: {list(cls().available_sensors.keys())}")
    
    @abstractmethod
    def open(self) -> bool:
        """
        打开传感器连接
        
        Returns:
            bool: 打开是否成功
        """
        pass
    
    @abstractmethod
    def close(self) -> bool:
        """
        关闭传感器连接
        
        Returns:
            bool: 关闭是否成功
        """
        pass
    
    @abstractmethod
    def parse_data(self, data: bytes) -> Optional[Dict[str, Union[float, int]]]:
        """
        解析传感器数据
        
        Args:
            data: 从传感器读取的原始数据
            
        Returns:
            包含distance(mm)等信息的字典，解析失败返回None
        """
        pass
    
    def get_distance(self) -> Optional[float]:
        """
        获取当前测距值(mm)
        
        Returns:
            float: 测距值(mm)，获取失败返回None
        """
        # 子类应该实现具体的获取距离逻辑
        logger.warning("基类get_distance方法被调用，子类应重写此方法")
        return None
    
    def list_available_sensors(self) -> Dict[str, str]:
        """
        获取可用的传感器类型列表
        
        Returns:
            Dict: 传感器类型和描述的字典
        """
        return self.available_sensors.copy()


if __name__ == "__main__":
    # 示例：使用Sensor_select创建传感器实例
    print("可用传感器类型:")
    base = TOF_Measure()
    for sensor_type, description in base.list_available_sensors().items():
        print(f"- {sensor_type}: {description}")
    
    # 示例：选择PH2501传感器
    try:
        sensor = TOF_Measure.Sensor_select("PH2501")
        print(f"成功创建传感器实例: {type(sensor).__name__}")
    except Exception as e:
        print(f"创建传感器实例失败: {e}")